﻿using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExcelAutomationRunner
{

    public class Sorter : ExcelApplicationBase
    {

        private string _path;
        private int _columnNum;

        /// <summary>
        /// Sorts num column in first worksheet.
        /// </summary>
        /// <param name="num">Column number to sort (1 based)</param>
        /// <param name="path">Path to Excel File</param>
        /// <returns></returns>
        public Tuple<bool, string> SortByColumn( int num, string path )
        {
            if ( File.Exists( path ) )
            {
                _path = path;
                _columnNum = num;
                return ProcessApplication();  // this calls Process below.
            }
            else
            {
                return new Tuple<bool, string>( false, "File does not exist: " + path );
            }
        }

        /// <summary>
        /// Todo: add secondary sort column (pass 2 column indexes to sort by).  Is third param or something.
        /// </summary>
        /// <param name="excel"></param>
        /// <returns></returns>
        protected override Tuple<bool, string> Process( Application excel )
        {
            try
            {
                var workbook = excel.Workbooks.Open( _path );
                Worksheet existingWorksheet = excel.Workbooks[1].Worksheets[1];
                existingWorksheet.UsedRange.Sort( excel.Columns[_columnNum], XlSortOrder.xlDescending );
                workbook.Save();
                workbook.Close();
                return new Tuple<bool, string>( true, "" );
            }
            catch ( Exception ex )
            {
                return new Tuple<bool, string>( false, ex.Message );
            }
        }

    }
}
